package com.czk.api.deleteData;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/6/3 15:34
 */
public class DeleteData {
    private static Connection connection = null;
    private static Admin admin = null;

    static {
        // 静态代码块初始化
        // 创建配置类
        Configuration configuration = HBaseConfiguration.create();
        // zookeeper连接
        configuration.set("hbase.zookeeper.quorum", "192.168.25.133");
        // 端口
        configuration.set("hbase.zookeeper.property.clientPort", "2181");
        //
        try {
            connection = ConnectionFactory.createConnection(configuration);
            admin = connection.getAdmin();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接
     */
    public static void close() {
        try {
            if (admin != null) {
                admin.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }

    }


    public static void main(String[] args) throws IOException {
        deleteData("stu", "1003", "info2", "phone");
    }

    /**
     * 删除数据的测试
     *
     * @param tableName 表名
     * @param rowKey    住建
     * @param cf        列族
     * @param cn        列
     * @throws IOException
     */
    public static void deleteData(String tableName, String rowKey, String cf, String cn) throws IOException {
        // 参数校验
        if (tableName == null || rowKey == null) {
            throw new RuntimeException("参数错误");
        }
        // 获取表对象
        Table table = connection.getTable(TableName.valueOf(tableName));
        // 构建删除对象
        // 当只指定rowKey时打的标记deleteFamily,相当于deleteAll
        Delete delete = new Delete(Bytes.toBytes(rowKey));
        // 删除最新的版本
        // delete.addColumn(Bytes.toBytes(cf), Bytes.toBytes(cn));
        // 删除列的全部版本
        delete.addColumns(Bytes.toBytes(cf), Bytes.toBytes(cn));
        // 删除
        table.delete(delete);
        // 关闭
        table.close();
        close();
    }
}
